﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TS.Bussiness;
using TS.Commons;
using TS.Entities;
using Wuqi.Webdiyer;

namespace Tranco
{
    public partial class SchedulePersonal : System.Web.UI.Page
    {
        private int _pageSize; // Number record display on gridview
        private int _pageIndex; // Number page display
        private string _filter; // Condition filter 
        private string _orderBy; // Condition order follow header on gridview
        private string _status;
        protected void Page_Load(object sender, EventArgs e)
        {
            _pageIndex = 1;
            _pageSize = 10;
            _status = drStatus.SelectedItem.Value.ToStringOrDefault();
            if (drStatus.SelectedItem.Value == " ")
                _status = @"Đang đi' or s.Status = N'Chưa đi' or s.Status is null or s.Status = N'Đang về";
            if (Session["TracoGroupId"].ToStringOrDefault() == "5")
            {
                drStatus.Items.Remove("Hoàn thành");
            }
            if (!IsPostBack)
            {
                drYear.Items.FindByValue(DateTime.Today.Year.ToStringOrDefault()).Selected = true;
                drMonth.Items.FindByValue(DateTime.Today.Month.ToStringOrDefault()).Selected = true;

                _orderBy = " StartDate";
                HiddenFieldStatusOrder.Value = " DESC ";
                HiddenFieldOrderBy.Value = _orderBy;
                _filter = HiddenFieldStringFilter.Value;
                BindData(_pageSize, _pageIndex, _filter, HiddenFieldOrderBy.Value + HiddenFieldStatusOrder.Value,
                    DateTime.Today.Year.ToStringOrDefault(),
                                                                DateTime.Today.Month.ToStringOrDefault(),
                                                                "", "", _status
                    );

            }

        }

        /// <summary>
        /// Bind Data
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="filter"></param>
        /// <param name="orderBy"></param>
        /// <param name="year"> </param>
        /// <param name="month"> </param>
        /// <param name="week"> </param>
        /// <param name="day"> </param>
        /// <param name="status"> </param>
        private void BindData(int pageSize, int pageIndex, string filter, string orderBy, string year, string month,
                                string week, string day, string status)
        {
            int totalRecord;
            var userBu = new UserBussiness();

            var bussiness = new ScheduleBussiness();
            if (Session["TracoUserId"] == null)
            {
                ClientAlert("Đăng nhập để xem thông tin lịch trình.");
                return;
            }
            string ownerId;
            var user = userBu.GetUserByUserId(Session["TracoUserId"].ToNumeric());
            if (user.GroupId == 5)
                ownerId = user.OwnerId.ToStringOrDefault();
            else
            {
                ownerId = "";
            }
            Collection<Schedule> collection = bussiness.ReadSchedulePaged(pageSize, pageIndex, filter, orderBy,
                                                                year, month, week, day, ownerId, _status,
                                                            out totalRecord);
            //if (collection != null)
            //    if (collection.Count == 0)
            //    {
            //        Schedule obj = new Schedule();
            //        obj.StartDateS = "No Data";
            //        collection.Add(obj);
            //    }
            GridViewList.DataSource = collection;
            GridViewList.DataBind();
            AspNetPager.RecordCount = totalRecord;
            AspNetPager.PageSize = pageSize;
        }

        /// <summary>
        /// Page Changing
        /// </summary>
        /// <param name="src"></param>
        /// <param name="e"></param>
        protected void AspNetPagerPageChanging(object src, PageChangingEventArgs e)
        {
            _pageIndex = e.NewPageIndex;
            _orderBy = HiddenFieldOrderBy.Value;
            if (!string.IsNullOrEmpty(_orderBy))
            {
                _orderBy = _orderBy + HiddenFieldStatusOrder.Value;
            }
            _filter = HiddenFieldStringFilter.Value;
            BindData(_pageSize, _pageIndex, _filter, _orderBy, drYear.SelectedItem.Value.ToStringOrDefault(),
                drMonth.SelectedItem.Value.ToStringOrDefault(), drWeek.SelectedItem.Value.ToStringOrDefault()
                , drDay.SelectedItem.Value.ToStringOrDefault()
                , _status
                );
        }

        /// <summary>
        /// FilterData
        /// </summary>
        protected void DataFilter()
        {
            //get filter
            _filter = HiddenFieldStringFilter.Value;
            //get orderby
            _orderBy = HiddenFieldOrderBy.Value;

            if (!string.IsNullOrEmpty(_orderBy))
            {
                _orderBy = _orderBy + HiddenFieldStatusOrder.Value;
            }
            //set property of page
            _pageIndex = 1;
            AspNetPager.CurrentPageIndex = _pageIndex;
            //load data
            BindData(_pageSize, _pageIndex, _filter, _orderBy, drYear.SelectedItem.Value.ToStringOrDefault(),
                drMonth.SelectedItem.Value.ToStringOrDefault(), drWeek.SelectedItem.Value.ToStringOrDefault()
                , drDay.SelectedItem.Value.ToStringOrDefault()
                , _status
                );
        }

        protected void GridViewListSorting(object sender, GridViewSortEventArgs e)
        {
            HiddenFieldOrderBy.Value = e.SortExpression;
            HiddenFieldStatusOrder.Value = HiddenFieldStatusOrder.Value.Equals(" ASC ") ? " DESC " : " ASC ";

            DataFilter();
        }

        private string UrlUpdate = "~/ScheduleDetail.aspx?sid=";
        private string UrlUpdateOwner = "~/OwnerDetail.aspx?ownerid=";
        private string UrlUpdateGateway = "~/GatewayDetail.aspx?gwid=";
        private string UrlUpdateNumber = "~/NumberBikeDetail.aspx?nbid=";

        /// <summary>
        /// GridViewListRowCommand
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridViewListRowCommand(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Owner")
            {
                var result = e.CommandArgument.ToNumeric();
                if (result > 0)
                {
                    Response.Redirect(UrlUpdateOwner + result);

                }

            }
            else
                if (e.CommandName == "Gateway")
                {
                    var result = e.CommandArgument.ToNumeric();
                    if (result > 0)
                    {
                        Response.Redirect(UrlUpdateGateway + result);
                    }

                }
                else if (e.CommandName == "NumberBike")
                {
                    var result = e.CommandArgument.ToNumeric();
                    if (result > 0)
                    {
                        Response.Redirect(UrlUpdateNumber + result);
                    }

                }
                else if (e.CommandName == "Schedule")
                {
                    var result = e.CommandArgument.ToNumeric();
                    if (result > 0)
                    {
                        Response.Redirect(UrlUpdate + result);
                    }

                }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            HiddenFieldStringFilter.Value = txtFindUser.Text;

            DataFilter();
        }

        protected void btnEnter_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in GridViewList.Rows)
            {
                CheckBox cbSelection = (CheckBox)row.FindControl("cbSelection");
                if (cbSelection.Checked)
                {
                    Schedule obj = new Schedule();
                    LinkButton linkButton = (LinkButton)row.FindControl("lbtContent");
                    obj.ScheduleId = linkButton.CommandArgument.ToNumeric();

                    ScheduleBussiness ub = new ScheduleBussiness();
                    if (ub.DeleteSchedule(obj) > 0)
                    {
                        ClientConfirm();
                    }
                    else
                    {
                        ClientAlert("Có lỗi xảy ra. Vui lòng kiểm tra lại.");
                    }
                }
            }
        }

        /// <summary>
        /// Message alert
        /// </summary>
        /// <param name="strAlert"></param>
        public void ClientAlert(string strAlert)
        {
            var strScript = new StringBuilder();
            strScript.Append("<script language=JavaScript>");
            string scriptString = string.Format(CultureInfo.CurrentCulture, @"window.alert('" + strAlert + "');</script> ");
            strScript.Append(scriptString);
            ClientScript.RegisterStartupScript(GetType(), "Pop", strScript.ToString());
        }

        /// <summary>
        /// Message confirm
        /// </summary>
        public void ClientConfirm()
        {
            var strScript = new StringBuilder();
            strScript.Append("<script language=JavaScript>");
            string scriptString = string.Format(CultureInfo.CurrentCulture, @"var result = window.confirm('Xóa thành công. Bạn có muốn load lại trang?'); " +
                     "if(result) location.href='/Views/ScheduleManagementOwner.aspx';</script>");
            strScript.Append(scriptString);
            ClientScript.RegisterStartupScript(GetType(), "Pop", strScript.ToString());
        }
    }
}